#include "UserInfo.h"

#include "_Global/Sqlite/Sqlite.h"
#include "_Global/GlobalClass.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

#include <QCryptographicHash>


bool UserInfo::checkBadWord(QString word)
{
    if(m_pSqliteDB == nullptr)return false;
    if (!m_pSqliteDB->isValid())
        return false;

    QString sql = QString("SELECT * FROM LMS_BadWords WHERE '%1' LIKE '%'||BadWord||'%'").arg(word);
    QSqlQuery query(*m_pSqliteDB->getDB());  //查询

    if(!query.exec(sql))
    {
        qCritical() << ("Query BadWord ERROR");
        qCritical() << (m_pSqliteDB->getDB()->lastError().text());
        qCritical() << (query.lastError().text());
        qCritical() << (sql);
        query.finish();
        return false;
    }

    //qDebug() << "query:" << sql;// << query.size();
    if(query.next())
    {
        qDebug() << "BadWord:" << query.value("BadWord");
        query.finish();
        return false;
    }

    query.finish();
    return true;
}








/*
bool UserInfo::loadUserInfo()
{
    if(m_pSqliteDB == nullptr)return false;
    if (!m_pSqliteDB->isValid())
        return false;

    QSqlQuery query(*m_pSqliteDB->getDB());  //查询

    QString sql;
    sql = QString("SELECT * FROM UserScoreInfo WHERE userid=%1").arg(m_LoginInfo.id);

    if(!query.exec(sql))
    {
        Debug_Leamus("Query ClassInfo Error");
        return false;
    }

    if(query.next())
    {
        //setScoreCount(query.value("score").toInt());
    }
    else
    {
        //setScoreCount(0);
        query.finish();

        sql = QString("INSERT INTO UserScoreInfo(userid,score) VALUES(%1,0)").arg(m_LoginInfo.id);
        if(!query.exec(sql))
        {
            Debug_Leamus("Query ClassInfo Error");
            query.finish();
            return false;
        }
    }
    query.finish();

    return true;

}

bool UserInfo::updateUserScoreInfo()
{
    if(m_pSqliteDB == nullptr)return false;
    if (!m_pSqliteDB->isValid())
        return false;

    QSqlQuery query(*m_pSqliteDB->getDB());  //查询

    QString sql;



    //sql = QString("INSERT INTO UserScoreRecord(scoreAdd) VALUES(%1)").arg(m_ScoreAdd);
    if(!query.exec(sql))
    {
        Debug_Leamus("Query ClassInfo Error");
        return false;
    }
    query.finish();

    //setScoreCount(scoreCount() + m_ScoreAdd);
    //m_ScoreAdd = 0;

    //sql = QString("UPDATE UserInfo SET score=%1 WHERE userid=%2").arg(ScoreCount()).arg(m_id);
    if(!query.exec(sql))
    {
        Debug_Leamus("Query ClassInfo Error");
        return false;
    }

    query.finish();
    return true;

}
*/

bool UserInfo::sl_qml_UserLogin(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    if(pInfo["LoginName"].toString().isEmpty()
            || pInfo["Password"].toString().isEmpty())
        return false;
    setUserName(pInfo["LoginName"].toString());
    m_LoginInfo.m_strPassword = pInfo["Password"].toString();
    m_LoginInfo.m_ClientStatus = UserInfo::Client_IsLoginingInfoServer;



    m_pInfoSocket->connectServer();
    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    QString authcode = "nEv7NeFNCceFjZdSjl";  //密码的盐
    QByteArray passMD5 = QCryptographicHash::hash ( (authcode + m_LoginInfo.m_strPassword).toLatin1(), QCryptographicHash::Md5 );
    passMD5 = QCryptographicHash::hash ( passMD5.toHex(), QCryptographicHash::Md5 );

    QString pass = QCryptographicHash::hash (m_LoginInfo.m_strPassword.toLatin1(), QCryptographicHash::Md5 ).toHex();
    //authcode = "###" + QString::fromLatin1(passMD5.toHex());
    //qDebug() << authcode;

    /*
    m_pInfoSocket->sendData(TRANSMIT_CLIENT_TYPE) << (qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT
                                << (qint16)INFO_SERVER_LOGIN
                                << userName()
                                << m_LoginInfo.password;
    m_pInfoSocket->send();*/
    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_LOGIN
        << userName()
        << pass
        << m_LoginInfo.m_nClientType
        << _Game_Version_
           ;
    emit s_SendCodeDataToServer(m_pInfoSocket,ba);

    return true;
}

bool UserInfo::sl_qml_UserReg(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    if(pInfo["LoginName"].toString().isEmpty()
            || pInfo["Password"].toString().isEmpty())
        return false;

    setUserName(pInfo["LoginName"].toString());
    m_LoginInfo.m_strPassword = pInfo["Password"].toString();
    //setNickName(pInfo["Nickname"].toString());
    //setSex(pInfo["sex"].toInt());

    m_LoginInfo.m_ClientStatus = UserInfo::Client_IsRegisteringInfoServer;



    m_pInfoSocket->connectServer();


    QString authcode = "nEv7NeFNCceFjZdSjl";  //密码的盐
    QByteArray passMD5 = QCryptographicHash::hash ( (authcode + m_LoginInfo.m_strPassword).toLatin1(), QCryptographicHash::Md5 );
    passMD5 = QCryptographicHash::hash ( passMD5.toHex(), QCryptographicHash::Md5 );

    QString pass = QCryptographicHash::hash (m_LoginInfo.m_strPassword.toLatin1(), QCryptographicHash::Md5 ).toHex();
    //authcode = "###" + QString::fromLatin1(passMD5.toHex());

    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    /*
    m_pInfoSocket->sendData(TRANSMIT_CLIENT_TYPE) << (qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENTREGISTER
                                << userName()
                                << nickName()
                                << m_LoginInfo.password
                                << sex();
    m_pInfoSocket->send();*/
    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_REGISTER
        << userName()
        //<< nickName()
        << pass
        << sex()
        << m_LoginInfo.m_nClientType
        << _Game_Version_
           ;
    emit s_SendCodeDataToServer(m_pInfoSocket,ba);

    //qDebug() << "注册:" << userName() << nickName() << m_LoginInfo.m_strPassword << sex();
    return true;
}

bool UserInfo::sl_qml_GameUserReg(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    QString nick = pInfo["Nickname"].toString();

    int nicklength = nick.length() + nonASCIICount(nick);
    if(nicklength < 4 || nicklength > 16)
    {
        qWarning() << "[!UserInfo]sl_qml_GameUserReg:" << nick << nicklength;
        emit s_regGameServerStatus(2);
        return false;
    }
    if(checkBadWord(nick) == false)
    {
        qWarning() << "[!UserInfo]sl_qml_GameUserReg2:" << nick << nicklength;
        emit s_regGameServerStatus(3);
        return false;
    }

    setNickName(pInfo["Nickname"].toString());
    setSex(pInfo["Sex"].toInt());
    setScoreCount(0);

    m_LoginInfo.m_ClientStatus = Client_IsRegisteringGameServer;
    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    /*m_pGameSocket->sendData(TRANSMIT_CLIENT_TYPE) << (qint16)GAME_SERVER_REQUEST <<
                                    << (qint16)GAME_SERVER_CLIENT
                                    << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO
                                  << m_LoginInfo.id
                                  << serverID()
                                  << nickName()
                                  << sex();
    m_pGameSocket->send();*/

    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)GAME_SERVER_REQUEST
        << (qint16)GAME_SERVER_CLIENT
        << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO
        << m_LoginInfo.m_unID
        << serverID()
        << nickName()
        << sex()
        << m_LoginInfo.m_nClientType
        << _Game_Version_
           ;
    emit s_SendCodeDataToServer(m_pGameSocket,ba);

    return true;
}

bool UserInfo::sl_qml_ChoiceGameServer(int gameServerID)
{
    if(m_mapGameServerInfo.count() == 0)
    {
        emit s_gameServerInfoStatus(-100);
        qCritical() << "[!UserInfo]选择游戏服务器ERROR:" << gameServerID;
        return false;
    }

    m_nGameServerId = gameServerID;
    _GameServerInfo *pGameServerInfo = m_mapGameServerInfo.value(QString::number(m_nGameServerId), QVariant::fromValue(nullptr))
            .value<_GameServerInfo*>();
    //((_GameServerInfo*)(m_mapGameServerInfo.value(m_nGameServerId)));

    if(pGameServerInfo == nullptr)
    {
        qCritical() << "[!UserInfo]选择游戏服务器ERROR！";
        return false;
    }

    //本地!!!???
    if(pGameServerInfo->m_strIP == "local")
    {
        int ret = -1;// = loadGameUserInfoLocal();
        if(ret == 1)
        {
            emit s_gameServerInfoStatus(-101);
            return true;
        }
        else if(ret == 0)
        {
            emit s_gameServerInfoStatus(-102);
            return true;
        }
        else
        {
            emit s_gameServerInfoStatus(-103);
            qCritical() << "[!UserInfo]登录游戏服务器出错！";
            return false;     //本地读取游戏用户信息
        }
    }
    else
    {
        m_pGameSocket->m_strIP = pGameServerInfo->m_strIP;
        m_pGameSocket->m_unPort = pGameServerInfo->m_unPort;

        qDebug() << "[UserInfo]游戏服务器:" << pGameServerInfo->m_strIP << pGameServerInfo->m_unPort;

        m_pGameSocket->connectServer();

        loadGameUserInfo();
        return true;
        //这里是网络读取代码
    }
}
/*
bool UserInfo::sendUserInfoToServer()
{
    switch(m_LoginInfo.m_ClientStatus)
    {
    case Client_IsLoginingInfoServer:
        {
            m_pInfoSocket->sendData(TRANSMIT_CLIENT_TYPE)<<(qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_LOGIN
                                   <<userName()
                                  <<m_LoginInfo.password;
            m_pInfoSocket->send();
        }
        break;
    case Client_IsRegisteringInfoServer:
        {
            m_pInfoSocket->sendData(TRANSMIT_CLIENT_TYPE)<<(qint16)INFO_SERVER_REQUEST << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_REGISTER
                                  <<userName()
                                 <<nickName()
                                <<m_LoginInfo.password
                               //<<sex()
                                  ;
            m_pInfoSocket->send();
        }
        break;
    case Client_IsRegisteringGameServer:
        {
            if(checkBadWord(nickName()) == false)
            {
                //emit s_regGameStatus(2);
                return true;
            }

            m_pInfoSocket->sendData(TRANSMIT_CLIENT_TYPE)<<(qint16)GAME_SERVER_REQUEST<<(qint16)GAME_SERVER_REGISTERGAMEUSERINFO
                                  <<m_LoginInfo.id
                                 //<<serverID()
                                <<nickName()
                               //<<sex()
                                  ;
            m_pInfoSocket->send();

            return true;
        }
        break;
    case Client_IsLoginingGameServer:
        {
        }
        break;
    default:
        ;
    }
    return true;
}
*/

QVariantMap UserInfo::sl_getUserLevelInfo(int score)
{
    QVariantMap info;
    if(!m_pSqliteDB->isValid())
        return info;

    QString sql = QString("SELECT * FROM LevelInfo WHere %1>=Score ORDER By Score DESC Limit 1")
            .arg(score);
    QSqlQuery query(*m_pSqliteDB->getDB());  //查询
    if(!query.exec(sql))
    {
        qCritical() << (m_pSqliteDB->getDB()->lastError().text());
        qCritical() << (query.lastError().text());
        qCritical() << (sql);
        query.finish();
        return info;
    }
    if(query.next())
    {
        info.insert("level", query.value("ID"));
        info.insert("name", query.value("Name"));
        info.insert("Score", query.value("Score"));
    }
    else
    {
        info.insert("level", 0);
        info.insert("name", "无");
        info.insert("Score", 0);
    }

    query.finish();
    return info;
}
